package com.ruoyi.web.controller.V2.web.conntroller;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.operation.service.IOperationHistoryService;
import com.ruoyi.system.afteruser.domain.SaleAfterUser;
import com.ruoyi.system.afteruser.service.ISaleAfterUserService;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author lz
 * @version 1.0
 * @date 2022/5/10 18:34
 */
@RestController
@RequestMapping("/other/web")
public class OhterWebController extends BaseController {
    @Autowired
    private ISaleAfterUserService saleAfterUserService;
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private IOperationHistoryService operationHistoryService;


    @Autowired
    private RedisCache redisCache;
    static String TOKEN_PANZHI = "";
    static String TOKEN_authorization = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJQWEI3LUJVU0lORVNTLkFQSSIsImV4cCI6MTcyNTI4NTI3MywiYXVkIjoiYWRtaW4iLCJuYmYiOjE3MjUyNDIwNzMsImlhdCI6MTcyNTI0MjA3MywidXNlciI6eyJ1c2VyX2lkIjoxMDAsInVzZXJfbmFtZSI6Ilx1NzlkZlx1NmUzOFx1NGU1MCIsIm51bWJlciI6Inp5bCIsImNvbnRhY3QiOiJcdTlhNmNcdTVmNjZcdThmODkiLCJxcSI6IjE4MzkzOTQ5Mzc2IiwidGVsZXBob25lIjoiMTgzOTM5NDkzNzYiLCJ3eCI6IjE4MzkzOTQ5Mzc2IiwiZ2FtZUlkcyI6WyIxMyIsIjI2IiwiMjMiLCIxMSIsIjQwIiwiMzIiLCIzMyIsIjEyIiwiMzYiLCIxNDgiLCI0MDkiXX19.qtPN8rJEYHHbK_5pLqOvC6Qlp6CdgBgqOWlaVeJIrqI";

    /**
     * 新增用户填报
     */
    //@Log(title = "用户填报", businessType = BusinessType.INSERT)
    @PostMapping("/afterUser/user")
    public AjaxResult afterUserAdd(@RequestBody SaleAfterUser saleAfterUser) {
        return toAjax(saleAfterUserService.insertSaleAfterUser(saleAfterUser));
    }

    /**
     * 新增用户填报
     */
    //@Log(title = "111", businessType = BusinessType.INSERT)
//    @GetMapping("/bargain/msg")
    public AjaxResult bargainMsg() {
        JSONObject result = new JSONObject();
        JSONObject redisResult = (JSONObject) redisCache.getCacheObject("BARGAIN_RESULT");
        if (Objects.nonNull(redisResult)){
            return AjaxResult.success(redisResult);
        }

        int panzhiCount = 0;
        try {
            String url = "https://api.pzds.com/api/web-client/v3/bargain/seller/list";
            getToken();
            JSONObject params = new JSONObject();
            JSONObject action = new JSONObject();
            action.put("bargainOrderPayStatus", null);
            action.put("status", "IN_PROGRESS");
            params.put("action", action);
            params.put("page", 1);
            params.put("pageSize", 10);
            String response = getPanZhi(url, params);
            System.out.println(response);
            if (CollectionUtils.isNotEmpty(JSONObject.parseObject(response).getJSONObject("data").getJSONArray("records"))) {
                List<JSONObject> data = JSONObject.parseArray(JSONObject.parseObject(response).getJSONObject("data").getString("records"), JSONObject.class);
                List<JSONObject> collect = data.stream().filter(s -> StringUtils.equals(s.getString("subStatusName"), "待卖家响应")).collect(Collectors.toList());
                panzhiCount = collect.size();
            }
        } catch (Exception e) {
            panzhiCount = 0;
        }
        result.put("panzhi", panzhiCount);
        // --------------------------------------------------
        int pangxieCount = 0;
        try {
            getPXToken();
            String url = "http://api-merchant.pxb7.com/business/bargain/list";
            Map<String, String> header = new HashMap<>();
            header.put("authorization", TOKEN_authorization);
            header.put("content-type", "application/json;charset=UTF-8");
            Map<String, String> params = new HashMap<>();
            params.put("game_account", "");
            params.put("keyword", "");
            params.put("page", "1");
            params.put("pageSize", "20");
            params.put("status", "1");
            try {
                String sendPost = HttpUtils.sendPost(url, JSONObject.toJSONString(params), header);
                List<JSONObject> data = JSONObject.parseArray(JSONObject.parseObject(sendPost).getJSONObject("data").getString("list"), JSONObject.class);
                long millis = System.currentTimeMillis() - 2 * 60 * 60 * 1000;
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd : HH:mm:ss");

                List<JSONObject> collect = data.stream().filter(d -> LocalDateTime.parse(d.getString("add_time"), dateTimeFormatter).atZone(ZoneId.of("UTC"))
                        .toInstant()
                        .toEpochMilli() > millis).collect(Collectors.toList());
                pangxieCount = collect.size();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            pangxieCount = 0;
        }
        result.put("pangxie", pangxieCount);
        redisCache.setCacheObject("BARGAIN_RESULT", result, 1, TimeUnit.MINUTES);

        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        Date date = new Date("2023-01-12 : 11:17:02");
        System.out.println(date.getTime());
    }
    public String getPanZhi(String url, JSONObject params) {

        // 生成 随机数 并生成sign  注意 &2147483647         &accessKey=3qXyB7uf
        StringBuilder sb = new StringBuilder();
        long PZTimestamp = System.currentTimeMillis();
        String Random = getRanString();
        sb.append("PZTimestamp=");
        sb.append(PZTimestamp);
        sb.append("&Random=");
        sb.append(Random);
        sb.append("&2147483647=");
        sb.append(JSONObject.toJSON(params));
        sb.append("&accessKey=3qXyB7uf");
        System.out.println(sb.toString());
        String b = sb.toString();
        try {
            b = URLEncoder.encode(b, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        b = b.replace("%26", "&");
        b = b.replace("%3D", "=");
        System.out.println(b);
        b = b.replaceAll("\\(", "%28");
        b = b.replaceAll("\\)", "%29");
        b = b.replaceAll("'", "%27");
        b = b.replaceAll("\\*", "%2A");
        b = b.replaceAll("~", "%7E");
        b = b.replaceAll("!|！", "%21");
        b = b.replaceAll("\\+", "%20");
        System.out.println(b);
        String sign = DigestUtils.md5Hex(b);
        System.out.println(sign);
        //开始拼装请求
        String response = HttpRequest.post(url)
                .header("Accept", "application/json, text/plain, */*")
                .header("PZTimestamp", String.valueOf(PZTimestamp))
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("Origin", "https://www.pzds.com")
                .header("PZPlatform", "pc")
                .header("PZVersion", "1.0.0")
                .header("PZVersionCode", "1")
                .header("Random", Random)
                .header("Referer", "https://www.pzds.com/")
                .header("sign", sign)
                .header("Token", TOKEN_PANZHI)
                .header("sec-ch-ua-mobile", "?0")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123 .0.0.0")
                .body(JSONObject.toJSONString(params)).execute().body();
        return response;
    }

    public void getToken() {
        String token = (String) redisCache.getCacheObject("PANZHI_BARGAIN_TOKEN");
        if (StringUtils.isNotEmpty(token)) {
            TOKEN_PANZHI = token;
            return;
        }
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("panzhi_bargainBack");
        String username = "";
        String password = "";
        for (SysDictData dictData : sysDictDataList) {
            if ("username".equals(dictData.getDictLabel())) {
                username = dictData.getDictValue();
            }
            if ("password".equals(dictData.getDictLabel())) {
                password = dictData.getDictValue();
            }
        }
        token = loginPanzhi(username, password);
        if (StringUtils.isNotEmpty(token)) {
            TOKEN_PANZHI = token;
            redisCache.setCacheObject("PANZHI_BARGAIN_TOKEN", token, 3, TimeUnit.MINUTES);
        }
    }

    public String loginPanzhi(String userName, String pwd) {
        String url = "https://api.pzds.com/api/web-client/v2/user/public/login/password";
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> action = new HashMap<>();
        params.put("phone", userName);
        String string = DigestUtils.md5Hex(pwd);
        params.put("password", string);
        params.put("openId", null);
        params.put("thirdType", null);
        params.put("unionId", null);
        action.put("action", params);

        // 生成 随机数 并生成sign  注意 &2147483647         &accessKey=3qXyB7uf
        StringBuilder sb = new StringBuilder();
        long PZTimestamp = System.currentTimeMillis();
        String Random = getRanString();
        sb.append("PZTimestamp=");
        sb.append(PZTimestamp);
        sb.append("&Random=");
        sb.append(Random);
        sb.append("&2147483647=");
        sb.append(JSONObject.toJSON(action));
        sb.append("&accessKey=3qXyB7uf");
        System.out.println(sb.toString());
        String b = sb.toString();
        try {
            b = URLEncoder.encode(b, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        b = b.replace("%26", "&");
        b = b.replace("%3D", "=");
        b = b.replaceAll("\\(", "%28");
        b = b.replaceAll("\\)", "%29");
        b = b.replaceAll("'", "%27");
        b = b.replaceAll("\\*", "%2A");
        b = b.replaceAll("~", "%7E");
        b = b.replaceAll("!|！", "%21");
        String sign = DigestUtils.md5Hex(b);
        //开始拼装请求
        String body = HttpRequest.post(url).header("Accept", "application/json, text/plain, */*")
                .header("PZTimestamp", String.valueOf(PZTimestamp))
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("Origin", "https://www.pzds.com")
                .header("PZPlatform", "pc")
                .header("PZVersion", "1.0.0")
                .header("PZVersionCode", "1")
                .header("Random", Random)
                .header("Referer", "https://www.pzds.com/")
                .header("sign", sign)
                .header("sec-ch-ua-mobile", "?0")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123 .0.0.0")
                .body(JSONObject.toJSONString(action)).execute().body();
        return JSONObject.parseObject(body).getString("data");
    }

    public static String getRanString() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }
        if (str.startsWith("0")) {
            str = str.replaceFirst("0", "1");
        }
        return str;
    }

    public void getPXToken() {
        String token = (String) redisCache.getCacheObject("PX_BARGAIN_TOKEN");
        if (StringUtils.isNotEmpty(token)) {
            TOKEN_authorization = token;
        }
        String url1 = "http://api-merchant.pxb7.com/business/login";
        Map<String, String> params1 = new HashMap<>();

        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("pangxie_bargainBack");
        for (SysDictData dictData : sysDictDataList) {
            if ("username".equals(dictData.getDictLabel())) {
                params1.put("user_name", dictData.getDictValue());
            }
            if ("password".equals(dictData.getDictLabel())) {
                params1.put("password", dictData.getDictValue());
            }
        }

        String response = com.ruoyi.system.outto.dto.yx7881.utils.HttpUtil.doPost(url1, params1);
        JSONObject jsonObject = JSONObject.parseObject(response);

        if ("200".equals(jsonObject.getString("code"))) {
            String data = jsonObject.getString("data");
            JSONObject jsonObject1 = jsonObject.parseObject(data);
            TOKEN_authorization = jsonObject1.getString("token");
            redisCache.setCacheObject("PX_BARGAIN_TOKEN" , token, 3, TimeUnit.MINUTES);
        }
    }


}
